package org.crspta.gohomenotes.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.crspta.gohomenotes.domain.PlayDateGoHomeNote;
import org.crspta.gohomenotes.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/playdategohomenotes")
@Controller
@RooWebScaffold(path = "playdategohomenotes", formBackingObject = PlayDateGoHomeNote.class)
public class PlayDateGoHomeNoteController {

    @Autowired
    private transient MailSender mailTemplate;

    @Autowired
    private transient SimpleMailMessage templateMessage;

    public void sendMessage(String mailTo, String message) {
        org.springframework.mail.SimpleMailMessage mailMessage = new org.springframework.mail.SimpleMailMessage(templateMessage);
        mailMessage.setTo(mailTo);
        mailMessage.setText(message);
        mailTemplate.send(mailMessage);
    }
    
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid PlayDateGoHomeNote playDateGoHomeNote, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, playDateGoHomeNote);
            return "playdategohomenotes/create";
        }
        uiModel.asMap().clear();
        playDateGoHomeNote.persist();
        
//        for (final Student guest: playDateGoHomeNote.getGuests()) {
//        	sendMessage("nathanward1234@gmail.com", "CRS PTA: Go Home Note Approval Request");
//        }
        
        return "redirect:/playdategohomenotes/" + encodeUrlPathSegment(playDateGoHomeNote.getId().toString(), httpServletRequest);
    }
}
